package org.hs.phd.odi.tracking.layers;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;

import org.hs.phd.common.simpleplayer.PlayerViewerLayer;
import org.hs.phd.common.simpleplayer.frameviewer.FrameViewer;
import org.hs.phd.odi.tracking.filters.TrackSelectionEvent;
import org.hs.phd.odi.tracking.tracker.TrackerUtils;

public class RectangleAnnotationLayer implements PlayerViewerLayer {
	
	private FrameViewer viewer;
	private boolean isEnabled;
	private int startX;
	private int startY;
	private int endX;
	private int endY;

	public RectangleAnnotationLayer(){
		this.isEnabled = true;
		reset();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// do nothing
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mousePressed(MouseEvent e) {
		startX = e.getX();
		startY = e.getY();		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		endX = e.getX();
		endY = e.getY();
		
		Rectangle rect = new Rectangle(startX, startY, endX - startX, endY - startY);
		
		if(rect.isEmpty()) return;

		Polygon modelPolygon = viewer.getTransformation().viewToModel(TrackerUtils.getAsPolygon(rect));
		
		viewer.repaint();
		viewer.getViewerController().fireEvent(new TrackSelectionEvent(modelPolygon));
		
		reset();
	}

	private void reset() {
		startX = - 1;
		startY = -1;
		endX = -1;
		endY = -1;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		if( startX == -1 ) return;
		
		endX = e.getX();
		endY = e.getY();
		
		viewer.repaint();
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// do nothing
	}

	@Override
	public void setViewer(FrameViewer viewer) {
		this.viewer = viewer;
	}

	@Override
	public void paint(Graphics g) {
		if(startX != -1 && startX != endX && startY != endY){

			Graphics2D g2 = (Graphics2D) g;
			g2.setColor(Color.CYAN);
			g2.drawRect(startX, startY, endX - startX, endY - startY);
		}
	}

	@Override
	public void setEnabled(boolean isEnabled) {
		this.isEnabled = isEnabled;
	}

	@Override
	public boolean isEnabled() {
		return isEnabled;
	}

}
